package com.quanyan.user.thread;

import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.CommonParameterEnum;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import com.quanyan.user.service.HttpClientService;
import com.quanyan.user.service.UserExtService;
import com.quanyan.user.service.UserInterestService;
import com.quanyan.user.service.UserMedalService;
import main.java.com.UpYun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Random;

/**
 * Created by zhang on 16/7/27.
 */
public class UserInitThread implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(UserInitThread.class);

    //upYun运行前先设置好以下三个参数
    private static final String BUCKET_NAME = "quncao";
    private static final String OPERATOR_NAME = "quncao";
    private static final String OPERATOR_PWD = "quncao888";

    private Integer uid;

    private TbLevelMapper levelMapper;

    private TbLevelParamMapper levelParamMapper;

    private TbCommonParameterMapper commonParameterMapper;

    private TbUserMapper userMapper;

    private UserInterestService userInterestService;

    private UserExtService userExtService;

    private UserMedalService userMedalService;

    private UserInfoMapper  userInfoMapper;

    private MyRedisTemplate myRedisTemplate;

    private HttpClientService httpClientService;

    public UserInitThread(Integer uid,
                          TbLevelMapper levelMapper,
                          TbLevelParamMapper levelParamMapper,
                          TbCommonParameterMapper commonParameterMapper,
                          TbUserMapper userMapper,
                          UserInterestService userInterestService,
                          UserExtService userExtService,
                          UserMedalService userMedalService,
                          UserInfoMapper userInfoMapper,
                          MyRedisTemplate myRedisTemplate,
                          HttpClientService httpClientService){
        this.uid = uid;
        this.levelMapper = levelMapper;
        this.levelParamMapper = levelParamMapper;
        this.commonParameterMapper = commonParameterMapper;
        this.userMapper = userMapper;
        this.userInterestService = userInterestService;
        this.userExtService = userExtService;
        this.userMedalService = userMedalService;
        this.userInfoMapper = userInfoMapper;
        this.myRedisTemplate = myRedisTemplate;
        this.httpClientService = httpClientService;
    }


    @Override
    public void run() {
        logger.info("开始用户初始化 uid：{}",uid);

        /**----------------------------------------初始化用户勋章开始--------------------------------------**/
        List<TbUserMedalRelation> userMedalRelationList = userMedalService.getUserMedalRelationList(uid);

        if (userMedalRelationList.isEmpty()) {
            userMedalService.initUserMedalList(uid);
            logger.info("用户勋章初始化完成 uid：{}",uid);
        }
        /**----------------------------------------初始化用户勋章结束--------------------------------------**/

        /**----------------------------------------初始化用户等级开始--------------------------------------**/
        List<TbLevel> levelList = this.getLevelList(uid, Constants.SystemLevelType.USER_XP_TYPE);
        if (levelList.isEmpty()) {
            List<TbLevelParam> levelParamList = this.getLevelParamList(1, 1);
            TbLevel level = new TbLevel();
            level.setType(Constants.SystemLevelType.USER_XP_TYPE.byteValue());
            level.setXp(0);
            level.setLevel(0);
            level.setCommonId(uid);
            if (levelParamList.isEmpty()) {
                level.setNextLevelXp(0);
            }else{
                level.setNextLevelXp(levelParamList.get(0).getXp());
            }
            this.insertLevel(level);
            logger.info("用户等级初始化完成 uid：{}",uid);
        }
        /**----------------------------------------初始化用户等级结束--------------------------------------**/

        /**----------------------------------------初始化用户拓展信息开始--------------------------------------**/
        //初始化用户背景图片
        List<TbCommonParameter> commonParameterList = this.getCommonParameterList(CommonParameterEnum.USER_SYSTEM_BG.getCode());
        int k=0;
        if (!commonParameterList.isEmpty()) {
            k = new Random().nextInt(commonParameterList.size());
        }
        TbUserExt userExt = new TbUserExt();
        userExt.setUid(uid);
        userExt.setBgUrl(commonParameterList.get(k).getParameterValue());
        userExtService.updateUserExt(userExt);
        logger.info("个人背景图片初始化成功：【{}】",uid);
        /**----------------------------------------初始化用户拓展信息结束--------------------------------------**/

        /**----------------------------------------初始化用户兴趣开始--------------------------------------**/
        TbUser user = this.getUser(uid);
        if (user != null) {
            String dsn = user.getDsn();
            if (!StringUtil.isBlankOrNull(dsn)) {
                List<TbUserInterest> userInterestList = this.userInterestService.getUserInterestList(UserConstants.USER_VISITOR,
                        uid,
                        dsn,
                        UserConstants.USER_INTEREST_IS_OBTAIN);
                if (userInterestList.isEmpty()) {
                    this.userInterestService.batchInsertUserInterest(uid,dsn,UserConstants.USER_REGISTER);
                }else{
                    for (TbUserInterest userInterest : userInterestList) {
                        userInterest.setUid(uid);
                        this.userInterestService.updateUserInterest(
                                userInterest,
                                null,
                                UserConstants.USER_VISITOR,
                                null,
                                dsn,
                                UserConstants.USER_INTEREST_IS_REGISTER);
                    }
                }

            }else{
                this.userInterestService.batchInsertUserInterest(uid,dsn,UserConstants.USER_REGISTER);
            }
        }
        /**----------------------------------------初始化用户兴趣结束--------------------------------------**/

        //第三方注册用户，用户图片上传到upyun
        if(user != null){
            uploadIconToUpyun(user);
        }
    }

    //第三方注册用户，用户图片上传到upyun
    private void uploadIconToUpyun(TbUser user) {
        if (user.getRegType() != null && user.getRegType() != 0) { //判断是否是第三方注册
            String icon = user.getIcon();
            if (StringUtil.isNotBlank(icon)) {
                InputStream inputStream = null;
                ByteArrayOutputStream swapStream = null;
                try {
                    String urlSplit[] = icon.split("/");
                    String fileLocation = "/user/icon/" + uid.toString() + urlSplit[urlSplit.length - 1];

                    URL url = new URL(icon);
                    inputStream = url.openStream();
                    swapStream = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int rc = 0;
                    while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
                        swapStream.write(buff, 0, rc);
                    }
                    byte[] bytes = swapStream.toByteArray();

                    UpYun upYun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
                    upYun.setTimeout(60); //设置超时时间
                    upYun.setDebug(false); // 设置是否开启debug模式，默认不开启
                    boolean result = upYun.writeFile(fileLocation, bytes, true); //上传图片到upyun

                    if (result) {
                        //更新icon和缓存
                        icon = "http://" + BUCKET_NAME + ".b0.upaiyun.com" + fileLocation; //获取回调地址
                        user.setIcon(icon);
                        String userKey = UserConstants.getUserRedisKey(uid);
                        userMapper.updateByPrimaryKeySelective(user);
                        myRedisTemplate.set(userKey, userMapper.selectByPrimaryKey(uid), 7);
                        String keyDetail = UserConstants.getUserDetailRedisKey(uid);
                        myRedisTemplate.set(keyDetail, userInfoMapper.findUserInfoDetail(uid), 7);
                        httpClientService.updateSetting(uid, null, 1, 1);
                    }

                } catch (Exception e) {
                    logger.error("获取第三方用户注册图片失败!");
                } finally {
                    try {
                        if (swapStream != null)
                            swapStream.close();
                        if (inputStream != null)
                            inputStream.close();
                    } catch (IOException e) {
                        logger.error("IO流关闭失败！");
                    }
                }
            }

        }
    }


    /**
     * 获取用户等级信息
     * @param uid
     * @param type
     * @return
     */
    public List<TbLevel> getLevelList(Integer uid,Integer type){
        TbLevelExample example = new TbLevelExample();
        example.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE).andCommonIdEqualTo(uid).andTypeEqualTo(type.byteValue());
        List<TbLevel> levelList = this.levelMapper.selectByExample(example);
        return levelList;
    }

    /**
     * 获取等级参数信息
     * @param type
     * @param level
     * @return
     */
    public List<TbLevelParam> getLevelParamList(Integer type,Integer level){
        TbLevelParamExample example = new TbLevelParamExample();
        example.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE).andTypeEqualTo(type.byteValue()).andLevelEqualTo(level);
        List<TbLevelParam> levelParamList = this.levelParamMapper.selectByExample(example);
        return levelParamList;
    }

    /**
     * 插入用户等级信息
     * @param level
     * @return
     */
    public int insertLevel(TbLevel level){
        int n = this.levelMapper.insertSelective(level);
        return n;
    }


    /**
     * 获取系统公共配置参数
     * @param parameterKey
     * @return
     */
    public List<TbCommonParameter> getCommonParameterList(String parameterKey){
        TbCommonParameterExample example = new TbCommonParameterExample();
        TbCommonParameterExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andParameterKeyEqualTo(parameterKey);
        List<TbCommonParameter> commonParameterList = this.commonParameterMapper.selectByExample(example);
        return commonParameterList;
    }

    /**
     * 获取个人信息
     * @param uid
     * @return
     */
    public TbUser getUser(Integer uid){
        TbUser user = this.userMapper.selectByPrimaryKey(uid);
        return user;
    }

}
